﻿using System;
using System.Collections.Generic;
using System.Text;
using ET;

namespace Marx
{
    public enum HostState
    {
        Starting,
        Running,
        Shutting,
    }

    public static class HostData
    {
        internal static HostState State = HostState.Starting;
        internal readonly static List<IAppStartup> Starters = new List<IAppStartup>();
        internal readonly static List<IAppShutdown> Shuters = new List<IAppShutdown>();
    }

    public static class HostExtension
    {
        public static void AddStarter(this IMarxHost host, IAppStartup starter)
        {
            HostData.Starters.Add(starter);
        }

        public static void RemoveStarter(this IMarxHost host, IAppStartup starter)
        {
            HostData.Starters.Remove(starter);
        }

        public static void AddShuter(this IMarxHost host, IAppShutdown shuter)
        {
            HostData.Shuters.Add(shuter);
        }

        public static void RemoveShuter(this IMarxHost host, IAppShutdown shuter)
        {
            HostData.Shuters.Remove(shuter);
        }

        public static void SetHostState(this IMarxHost host, HostState state)
        {
            HostData.State = state;
        }

        public static HostState GetHostState(this IMarxHost host)
        {
            return HostData.State;
        }

        public static async ETTask StartServer(this IMarxHost host)
        {
            foreach(var item in HostData.Starters)
            {
                await item.Startup();
            }
            Game.EventSystem.Publish(new EventType.AppReady());
        }

        public static async ETTask StopServer(this IMarxHost host)
        {
            host.SetHostState(HostState.Shutting);
            foreach(var item in HostData.Shuters)
            {
                await item.Shutdown();
            }
            Game.EventSystem.Publish(new EventType.AppCleanup());
        }
    }
}
